package com.globaldom.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.globaldom.model.CountryDetail;
import com.globaldom.model.Person;
import com.globaldom.utils.MemCacheManager;
import com.globaldom.utils.PMF;
import com.google.appengine.api.utils.SystemProperty;
import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.appengine.repackaged.org.json.JSONObject;

@Controller
@RequestMapping(value = "/mainpage")
public class MainPage {
	public MainPage() {
	}
	private static final Logger log = Logger.getLogger(MainPage.class.getName());

	// String appid="128354671037";
	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(HttpServletRequest request, HttpServletResponse response, Model model,
			HttpSession session) {

		response.addHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
		boolean prod = false;
		if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
			prod = true;
		}
		//
		try {
			String signed_request = request.getParameter("signed_request");
			int dotindex = signed_request.indexOf(".");
			// String sign=signed_request.substring(0, dotindex);
			String payload = signed_request.substring(dotindex + 1);

			JSONObject obj = new JSONObject(new String(Base64.decode(payload)));
			if (!obj.has("oauth_token")) {
				response.addHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
				model.addAttribute("prod", prod);
				return "mainpage";// or return to "welcome"!

			}
			// String algorithm=obj.getString("algorithm");
			// String expires=obj.getString("expires");

			String oauth_token = obj.getString("oauth_token");
			String personID = obj.getString("user_id");
			session.setAttribute("personID", personID);
			session.setAttribute("fbtoken", oauth_token);
			java.util.Map<String, Object> m = new HashMap<String, Object>();
			m.put("personID", personID);
			m.put("fbtoken", oauth_token);

			try {
				response.addCookie(new Cookie("a", session.getId() + personID.toString()));
				MemCacheManager.putAuthStats(session.getId() + personID.toString(), m);
			} finally {
			}

			PersistenceManager pm = PMF.get().getPersistenceManager();

			Person person = pm.getObjectById(Person.class, personID);
			if (null == person) {

				String fname = null, lname = null;

				Cookie[] cookies = request.getCookies();
				if (cookies != null) {
					for (int i = 0; i < cookies.length; i++) {
						Cookie cookie = cookies[i];
						if ((cookie.getName().equals("first_name"))) {
							fname = cookie.getValue();
						} else if ((cookie.getName().equals("last_name"))) {
							lname = cookie.getValue();
						}
					}
				}
				if (null == fname) {
					obj = fetchURL("http://graph.facebook.com/" + personID + "?fields=first_name,last_name");
					if (obj != null) {
						fname = obj.getString("first_name");
						lname = obj.getString("last_name");
					} else {
						fname = "Player" + Math.round(Math.random() * 1000000);
						lname = " ";

					}

				}

				person = new Person();
				person.setFirstName(fname);
				person.setLastName(lname);
				person.setId(personID);
				person.setKarma(0);
				person.setLevel(1);
				person.setPowerLevel(100);
				person.setMaxCivilians(75);
				pm.makePersistent(person);
				pm.close();

			}

			if (person.getCountryCode() != null) {
				session.setAttribute("firsttime", "false");
				return "redirect:/resource";
			}

			List<CountryDetail> list = null;
			list = CountryDetail.findAllCountries();
			if (null == list || list.size() < 1)
				list = populateCountries();
			model.addAttribute("countryDetailList", list);
			return "country";

		} catch (Exception ex) {
			log.severe("Exception in Main Page" + ex.getLocalizedMessage());
			ex.printStackTrace();
			return "mainpage";
		}

	}

	private List<CountryDetail> populateCountries() {
		List<CountryDetail> list = new ArrayList<CountryDetail>();

		CountryDetail cd = new CountryDetail();
		cd.setId(1l);
		cd.setCflag("usa.png");
		cd.setCCode("US");
		cd.setCName("USA");
		list.add(cd);

		CountryDetail cd1 = new CountryDetail();
		cd1.setCflag("china.png");
		cd1.setCCode("CN");
		cd1.setCName("China");
		cd1.setId(2l);

		list.add(cd1);

		CountryDetail cd2 = new CountryDetail();
		cd2.setCflag("india.png");
		cd2.setCCode("IN");
		cd2.setCName("India");
		cd2.setId(3l);
		list.add(cd2);

		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.makePersistentAll(list);
		pm.close();
		return list;
	}

	public JSONObject fetchURL(String u) {
		String retStr = "";
		try {
			URL url = new URL(u);
			BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				retStr += line;

			}

			reader.close();
			return new JSONObject(retStr);

		} catch (MalformedURLException e) {
			// ...
		} catch (IOException e) {
			// ...
		} catch (Exception ex) {

		}
		return null;

	}

	@RequestMapping(method = RequestMethod.POST)
	protected String storeCountries(@RequestParam String cCode, Model model) throws Exception {
		model.addAttribute("cd", cCode);
		return "location";
	}
}
